package hu.myai.triggers.bullish;

import hu.myai.api.tick.AbstractTickProvider;
import hu.myai.api.triggers.AbstractTrigger;
import hu.myai.indicators.pivot.LastLowIndicator;
import hu.myai.indicators.tick.TickIndicator;
import hu.myai.model.IndicatorVO;
import hu.myai.model.TriggerVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * If the third low is not going lower then previous 2 than it is a turn
 * bollinger TODO test with real data
 *
 * @author bozbalint
 *
 * */

public class TurnAtSupportTrigger extends AbstractTrigger {

    Double firstLow;

    int firstLowTimestamp;

    int timestamp;

    /**
     * The object used when logging debug,errors,warnings and info.
     * */
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    public TurnAtSupportTrigger(String name, AbstractTickProvider tick) {
        super(name, tick);
    }

    private String lastLowID;
    public void setLastLowIndicator(double parameter) {
        lastLowID = register(new LastLowIndicator(parameter));
    }

    private String tickID;
    public void setTickIndicatorParameter(double parameter) {
        tickID = register(new TickIndicator(TickIndicator.FEEL));
    }

    @Override
    protected TriggerVO triggerCalculation() {

        IndicatorVO secondLowIndicator = indicatorMap.get(lastLowID);
        IndicatorVO tickIndicator = indicatorMap.get(tickID);

        // ignore calculation if no indicator value
        if (secondLowIndicator == null || tickIndicator == null) {
            return null;
        }

        // init
        if (firstLow == null) {
            firstLow = secondLowIndicator.getValue();
            return null;
        }

        double expectedSupport = (timestamp / firstLowTimestamp) * (secondLowIndicator.getValue() - firstLow)
                + firstLow;
        timestamp++;

        TriggerVO trigger = null;

        // if it is close but above
        if ((expectedSupport / tickIndicator.getValue()) < 1.01 && expectedSupport < tickIndicator.getValue()) {
            trigger = new TriggerVO();
            trigger.setTick(lastTick);
            trigger.setRisk(20);
            trigger.setTradeType(TriggerVO.BUY_ONMARKET);
            log.debug(trigger.toString());
        }

        firstLow = secondLowIndicator.getValue();
        firstLowTimestamp = timestamp;

        return trigger;
    }
}
